<template>
  <div>
    <vab-card>
      <template #header>
        <span class="leve_title">库存明细查询</span>
      </template>
      <template #default>
        <el-form
          :ref="(el) => (searchFormRef = el)"
          :model="searchForm"
          label-width="130px"
          class="form_search composite_form"
        >
          <el-row :gutter="24">
            <el-col
              v-for="(item, i) in CheckDetailSearch"
              :key="i"
              :xs="24"
              :sm="12"
              :md="12"
              :lg="8"
              :xl="8"
              v-show="(!isMore && i < 1) || isMore"
            >
              <!-- 默认项 -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  v-model.trim="searchForm[item.prop]"
                  :multiple="item.multiple"
                  :options="selectOptions(item.prop)"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- autocomplete -->
              <el-form-item
                v-if="item.type == 'autocomplete'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabAutoFrom
                  v-model.trim="searchForm[item.prop]"
                  :list="selectOptions(item.prop)"
                />
              </el-form-item>
              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-input
                  clearable
                  placeholder="请输入"
                  class="width_100 height_auto"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'time'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-date-picker
                  clearable
                  placeholder="请选择"
                  type="datetimerange"
                  class="width_100 height_auto"
                  :format="TimeFormat"
                  :default-time="DefaultTime"
                  v-model="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- 一级类目 -->
              <el-form-item
                v-if="item.type == 'select_1'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-select
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  class="width_100 height_auto"
                  :multiple="item.multiple"
                  :filterable="item.multiple"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                  @change="
                    (value: string) => {
                      _ProductSearchClass(value)
                    }
                  "
                >
                  <el-option
                    clearable
                    v-for="(jtem, j) in selectOptions(item.prop)"
                    :key="jtem.value"
                    :label="jtem.label"
                    :value="jtem.value"
                  />
                </el-select>
              </el-form-item>
              <!-- 二级类目 -->
              <el-form-item
                v-if="item.type == 'select_2'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  v-if="classTwoList.length"
                  :options="classTwoList"
                  :multiple="item.multiple"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
            </el-col>
            <!-- 复合查询 -->
            <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
              <div class="flex">
                <span class="composite">
                  <el-select
                    class="composite_label"
                    v-model="compositeValue"
                    @change="handleComposite"
                  >
                    <el-option
                      v-for="item in CheckDetailCompositeSearch"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </span>
                <!-- 日期类 -->
                <el-date-picker
                  v-if="
                    compositeValue == 'product_date' ||
                    compositeValue == 'expire_date'
                  "
                  clearable
                  placeholder="请选择"
                  type="datetimerange"
                  class="width_100 height_auto"
                  :format="TimeFormat"
                  :default-time="DefaultTime"
                  v-model="datePickerValue"
                  @change="handleDatePicker"
                  @keyup.enter.native="onkeydown"
                />
                <!-- 区间类 -->
                <VabRangeForm v-else :ref="(el) => (vabRangeFormRef = el)" />
              </div>
            </el-col>
            <el-col
              :xs="24"
              :sm="24"
              :md="12"
              :lg="isMore ? 16 : 8"
              :xl="isMore ? 16 : 8"
            >
              <div class="flex_just_end">
                <el-button size="small" type="primary" @click="handleSearch()">
                  查询
                </el-button>
                <el-button size="small" @click="resetForm(searchFormRef)">
                  重置
                </el-button>
                <div class="sqFontSize" @click="isMore = !isMore">
                  更多
                  <el-icon v-if="isMore"><ArrowUp /></el-icon>
                  <el-icon v-else><ArrowDown /></el-icon>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </vab-card>
    <!-- 主 -->
    <vab-card shadow="always">
      <template #header>
        <span class="leve2_title">库存明细列表</span>
      </template>
      <el-table
        border
        height="520"
        style="width: 100%"
        :data="data.dataSource"
        v-loading="data.loading"
      >
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            <span
              class="ellipsis"
              v-text="(data.pageNum - 1) * data.pageSize + (scope.$index + 1)"
            ></span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, i) in data.cloums"
          :key="i"
          :width="item.width"
          :prop="item.prop"
          :label="item.label"
          :align="
            item.type == 'money' || item.type == 'number' ? 'right' : 'center'
          "
        >
          <template #default="scope">
            <!-- 自定义 -->
            <div v-if="item.type == 'custom'">
              <span
                class="ellipsis link text_right"
                @click="
                  () => {
                    orderDialogRef.open(scope.row, 1)
                  }
                "
              >
                {{ FieldFormat(scope.row[item.prop], 'number') }}
              </span>
            </div>
            <!-- 正常 -->
            <div v-else class="ellipsis">
              {{ FieldFormat(scope.row[item.prop], item.type) }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          label="主仓库存明细账"
          align="center"
          width="130"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleLink(scope.row)"
            >
              主仓明细账
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex_just_end">
        <el-pagination
          background
          small="small"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, prev, pager, next,sizes, jumper"
          :page-sizes="[20, 50, 100, 200]"
          :pager-count="10"
          :total="data.count"
          @current-change="handlePageNum"
          @size-change="handlePageSize"
        />
      </div>
    </vab-card>
    <!-- 订单弹窗 -->
    <OrderDialog :ref="(el) => (orderDialogRef = el)" />
  </div>
</template>
<!-- 库存查询 -->
<script lang="ts" setup>
  defineOptions({
    name: 'InventoryDetailCheck',
  })
  /**
   * @import
   */
  import {
    CheckDetailSearch,
    OtherOutSearchSelect,
    CheckDetailCloums,
    CheckDetailCompositeSearch,
  } from './components/tools'
  import {
    FieldFormat,
    TimeFormat,
    DefaultTime,
    DateFormat,
  } from '~/src/utils/utils'
  import { ElMessage, FormInstance } from 'element-plus'
  import {
    getInventorySearch,
    getInventoryStockBatch,
  } from '~/src/api/dms/inventory'
  import { productSearchClass } from '~/src/api/dms/product'
  import OrderDialog from './components/OrderDialog.vue'
  /**
   * @var
   */
  const router = useRouter()
  const searchFormRef = ref<any>(null)
  const vabRangeFormRef = ref<any>(null)
  const orderDialogRef = ref<any>()
  const searchForm = reactive<any>({})
  const data = reactive<any>({
    dataSource: [],
    cloums: [],
    pageNum: 1,
    pageSize: 20,
    count: 0,
    search: {},
  })
  data.dataSource = []
  data.cloums = CheckDetailCloums

  // 复合体
  const compositeValue = ref('quantity')
  const datePickerValue = ref<any>(null)
  let isCheck = ref(false)
  let isMore = ref(false)
  let classTwoList = ref<any>([])
  // 订单占有弹窗
  let orderVisible = ref(false)
  /**
   * @method
   */
  const handleSearch = async () => {
    isCheck.value = true
    await _GetProductList()
    ElMessage({ message: '查询成功', type: 'success' })
  }
  // 重置
  const resetForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    isCheck.value = false
    datePickerValue.value = null
    compositeValue.value = 'quantity'
    if (vabRangeFormRef.value) vabRangeFormRef.value.reset()
    await formEl.resetFields()
    await _GetProductList()

    ElMessage({
      message: '重置成功',
      type: 'success',
    })
  }
  // 回车
  const onkeydown = (value: any) => {
    isCheck.value = true
    _GetProductList()
  }
  // 复合筛选
  const handleComposite = (value: any) => {
    vabRangeFormRef.value.reset()
    datePickerValue.value = null
  }
  // 跳转
  const handleLink = (row: any) => {
    router.push({
      path: '/inventory/warehouse',
      query: {
        stock_id: row.id,
        from: 'detailCheck',
      },
    })
  }
  // 日期事件
  const handleDatePicker = (date: any, mode: any, view: any) => {
    if (!date) datePickerValue.value = null
  }
  // 页码
  const handlePageNum = (value: any) => {
    data.pageNum = value
    _GetProductList()
  }
  // 页数
  const handlePageSize = (value: any) => {
    data.pageSize = value
    _GetProductList()
  }

  // 筛选项格式化
  const selectOptions = (value: string) => {
    if (JSON.stringify(data.search) == '{}') return
    return OtherOutSearchSelect(data.search, value)
  }

  // 获取数据
  const _GetProductList = async () => {
    data.loading = true

    // 解构区间
    let vStart = ''
    let vEnd = ''
    if (vabRangeFormRef.value) {
      vStart = vabRangeFormRef.value.vStart
      vEnd = vabRangeFormRef.value.vEnd
    }

    // 复合项
    const composite = compositeValue.value
    let datePicker: any = null
    if (datePickerValue.value) datePicker = datePickerValue.value

    // 未点击查询
    let _searchForm = { ...searchForm }
    if (!isCheck.value) {
      _searchForm = {}
      vStart = ''
      vEnd = ''
      datePicker = null
    }

    const query = {
      page: data.pageNum,
      limit: data.pageSize,
      filter: {
        assistant_id: _searchForm.assistant_id || '', // 品牌
        class_id1: _searchForm.class_id1 || '', // 一级类目
        class_id2: _searchForm.class_id2 || '', // 二级类目
        xl_id: _searchForm.xl_id || '', // 系列
        barcode: _searchForm.barcode || '', // 条码
        number: _searchForm.number || '', // 产品编码
        name: _searchForm.name || '', // 产品名称
        batch_no: _searchForm.batch_no || '', // 批次
        quantity_start: composite == 'quantity' ? vStart : '', // 总库存开始
        quantity_end: composite == 'quantity' ? vEnd : '', // 总库存结束
        order_own_num_start: composite == 'order_own_num' ? vStart : '', // 订单占有开始
        order_own_num_end: composite == 'order_own_num' ? vEnd : '', // 订单占有结束
        sending_num_start: composite == 'sending_num' ? vStart : '', // 待发货量开始
        sending_num_end: composite == 'sending_num' ? vEnd : '', // 待发货量结束
        available_num_start: composite == 'available_num' ? vStart : '', // 可用库存期开始
        available_num_end: composite == 'available_num' ? vEnd : '', // 可用库存结束
        procure_num_start: composite == 'procure_num' ? vStart : '', // 采购在途开始
        procure_num_end: composite == 'procure_num' ? vEnd : '', // 采购在途结束
        allocate_num_start: composite == 'allocate_num' ? vStart : '', // 调拨在途开始
        allocate_num_end: composite == 'allocate_num' ? vEnd : '', // 调拨在途结束
        product_date_start:
          composite == 'product_date' && datePicker
            ? DateFormat(datePicker[0])
            : '', // 生产日期开始
        product_date_end:
          composite == 'product_date' && datePicker
            ? DateFormat(datePicker[1])
            : '', // 生产日期结束
        expire_date_start:
          composite == 'expire_date' && datePicker
            ? DateFormat(datePicker[0])
            : '', // 有效期开始
        expire_date_end:
          composite == 'expire_date' && datePicker
            ? DateFormat(datePicker[1])
            : '', // 有效期结束
      },
    }
    try {
      const res = await getInventoryStockBatch({ ...query })
      data.dataSource = res.data.list
      data.count = res.data.count
      data.loading = false
    } catch (error) {}
  }
  // 其他出入库筛选项
  const _GetProductSearch = async () => {
    try {
      const res = await getInventorySearch()
      await res.data.brand.push({ entry_id: '', name: '空' })
      await res.data.series.push({ id: '', data_title: '空' })
      await res.data.batch.unshift({ batch_no: '空' })
      data.search = await res.data
      classTwoList.value = selectOptions('class_id2')
    } catch (error) {}
  }
  // // 二级分类
  const _ProductSearchClass = async (class_id: any) => {
    classTwoList.value = []
    try {
      const res = await productSearchClass({ class_id })
      classTwoList.value = res.data.map((item: any) => {
        return {
          value: item.id,
          label: item.data_title,
        }
      })
    } catch (error) {}
  }

  onMounted(() => {
    _GetProductList()
    _GetProductSearch()
  })
</script>

<style lang="scss" scoped>
  @import '../../components/public.scss';
</style>
